package com.veo.controller;

import com.sun.org.apache.regexp.internal.RE;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Controller
public class FormFileController {


    @GetMapping("form_layouts")
    public String toFormFile(){
        return "form/form_layouts";
    }


    @PostMapping("/uploadFiles")
    public String uploadFiles(
            @RequestParam("email")String email,
            @RequestParam("username")String username,
            @RequestPart("headerImg")MultipartFile headerImg,
            @RequestPart("photos")MultipartFile[] photos, HttpServletRequest request) throws IOException {

        log.info("上传的信息：email={},username={},headerImg={},photos={}",
                email,
                username,
                headerImg.getSize(),
                photos.length);

        String path = request.getServletContext().getRealPath("/uploads");

        String originalFilename = headerImg.getOriginalFilename();
        String fileName = "";
        fileName = username + "-" + UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));


        String s = ServletUriComponentsBuilder.fromContextPath(request).path("/uploads").toString();
        System.out.println("s:"+s);


        File file = new File(path + "/" +fileName);
        if (!file.exists()){
            System.out.println(file.getAbsoluteFile());
        }

        headerImg.transferTo(new File(path,fileName));


        return "redirect:main.html";
    }
}
